import React, { useState, useEffect } from 'react';
import { toast } from '@/lib/toast-with-audio';
import { useTheme } from '@/hooks/useTheme';
import { roleApi, type Role } from '@/store/role';
import { motion } from 'framer-motion';

// 状态徽章组件
const StatusBadge: React.FC<{ status: number }> = ({ status }) => {
  const statusText = status === 1 ? '启用' : '停用';
  const className = status === 1 
    ? 'bg-green-100 dark:bg-green-900 text-green-700 dark:text-green-300'
    : 'bg-red-100 dark:bg-red-900 text-red-700 dark:text-red-300';
  
  return (
    <span className={`px-2 py-1 text-xs font-medium rounded-full ${className}`}>
      {statusText}
    </span>
  );
};

export default function Roles() {
  const { isDark } = useTheme();
  const [searchTerm, setSearchTerm] = useState('');
  const [statusFilter, setStatusFilter] = useState('all');
  const [roles, setRoles] = useState<Role[]>([]);
  const [loading, setLoading] = useState(false);
  
  // 加载角色数据
  const loadRoles = async (search?: string, status?: string) => {
    setLoading(true);
    try {
      const response = await roleApi.getRoles({
        search: search || undefined,
        status: status === 'all' ? undefined : (status === '启用' ? 1 : 0)
      });
      if (response.success) {
        setRoles(response.data);
      } else {
        toast(response.message || '获取角色列表失败');
      }
    } catch (error) {
      console.error('加载角色数据失败:', error);
      toast('加载角色数据失败');
    } finally {
      setLoading(false);
    }
  };
  
  // 页面加载时获取所有角色数据
  useEffect(() => {
    loadRoles();
  }, []);
  
  // 过滤角色数据（前端过滤，用于搜索和状态筛选）
  const filteredRoles = roles.filter(role => {
    const matchesSearch = role.name.toLowerCase().includes(searchTerm.toLowerCase()) || 
                          role.description.toLowerCase().includes(searchTerm.toLowerCase());
    const matchesStatus = statusFilter === 'all' || 
                         (statusFilter === '启用' && role.status === 1) ||
                         (statusFilter === '停用' && role.status === 0);
    
    return matchesSearch && matchesStatus;
  });
  
  const handleSearch = (e: React.KeyboardEvent<HTMLInputElement>) => {
    if (e.key === 'Enter') {
      // 按回车键时进行后端搜索
      loadRoles(searchTerm, statusFilter);
    }
  };
  
  // 搜索输入变化时进行前端过滤（不再触发后端请求）
  useEffect(() => {
    // 这里不再自动触发后端请求，只进行前端过滤
    // 用户可以通过回车键或搜索按钮手动触发后端搜索
  }, [searchTerm, statusFilter]);
  
  const handleCreateRole = async () => {
    try {
      // 这里可以添加创建角色的表单逻辑
      toast('新建角色功能开发中');
    } catch (error) {
      console.error('创建角色失败:', error);
      toast('创建角色失败');
    }
  };
  
  const handleEditRole = async (roleId: number) => {
    try {
      // 这里可以添加编辑角色的表单逻辑
      toast(`编辑角色 ${roleId} 功能开发中`);
    } catch (error) {
      console.error('编辑角色失败:', error);
      toast('编辑角色失败');
    }
  };
  
  const handleToggleStatus = async (roleId: number, currentStatus: number) => {
    try {
      const newStatus = currentStatus === 1 ? 0 : 1;
      const response = await roleApi.toggleRoleStatus(roleId, newStatus);
      
      if (response.success) {
        toast(response.message || `角色状态已${newStatus === 1 ? '启用' : '禁用'}`);
        // 重新加载数据
        loadRoles();
      } else {
        toast(response.message || '切换角色状态失败');
      }
    } catch (error) {
      console.error('切换角色状态失败:', error);
      toast('切换角色状态失败');
    }
  };
  
  return (
    <div>
      <div className="mb-6">
        <motion.div 
          className="mb-8"
          initial={{ opacity: 0, y: 20 }}
          animate={{ opacity: 1, y: 0 }}
          transition={{ duration: 0.5 }}
        >
        <h1 className="text-2xl font-bold text-gray-800 dark:text-gray-100">角色管理</h1>
        <p className="text-gray-600 dark:text-gray-400 mt-1">管理系统角色和权限分配</p>
        </motion.div>
      </div>
      
      {/* 工具栏 */}
      <div className="flex justify-between items-center mb-6">
        <div className="flex items-center space-x-4">
          <div className="relative">
            <input 
              type="text" 
              placeholder="搜索角色..." 
              className="py-2 pl-10 pr-4 border border-gray-300 dark:border-gray-600 rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-gray-100"
              value={searchTerm}
              onChange={(e) => setSearchTerm(e.target.value)}
              onKeyDown={handleSearch}
            />
            <i className="fa-solid fa-search absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400 dark:text-gray-500"></i>
          </div>
          
          <select 
            className="py-2 pl-3 pr-8 border border-gray-300 dark:border-gray-600 rounded-lg appearance-none focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent dark:bg-gray-700 dark:text-gray-100"
            value={statusFilter}
            onChange={(e) => setStatusFilter(e.target.value)}
          >
            <option value="all">全部状态</option>
            <option value="启用">启用</option>
            <option value="禁用">禁用</option>
          </select>
          
          <button 
            className="flex items-center bg-blue-600 hover:bg-blue-700 text-white py-2 px-4 rounded-lg transition-colors duration-300"
            onClick={() => loadRoles(searchTerm, statusFilter)}
          >
            <i className="fa-solid fa-search mr-2"></i>
            搜索
          </button>
        </div>
        
        <button 
          className="flex items-center bg-blue-600 hover:bg-blue-700 text-white py-2 px-4 rounded-lg transition-colors duration-300"
          onClick={handleCreateRole}
        >
          <i className="fa-solid fa-plus mr-2"></i>
          新建角色
        </button>
      </div>
      
      {/* 加载状态 */}
      {loading && (
        <div className="flex justify-center items-center py-12">
          <div className="animate-spin rounded-full h-12 w-12 border-b-2 border-blue-600"></div>
        </div>
      )}
      
      {/* 空状态 */}
      {!loading && filteredRoles.length === 0 && (
        <div className="text-center py-12">
          <i className="fa-solid fa-users-slash text-4xl text-gray-300 dark:text-gray-600 mb-4"></i>
          <p className="text-gray-500 dark:text-gray-400">暂无角色数据</p>
        </div>
      )}
      
      {/* 角色列表 */}
      {!loading && filteredRoles.length > 0 && (
        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
          {filteredRoles.map((role) => (
          <div key={role.id} className="bg-white dark:bg-gray-800 rounded-xl shadow-sm border border-gray-200 dark:border-gray-700 p-6">
            <div className="flex justify-between items-start mb-4">
              <h3 className="text-lg font-semibold text-gray-800 dark:text-gray-100">{role.name}</h3>
              <StatusBadge status={role.status} />
            </div>
            
            <p className="text-gray-600 dark:text-gray-400 text-sm mb-4">{role.description}</p>
            
            <div className="mb-4">
              <div className="flex justify-between text-sm text-gray-500 dark:text-gray-400 mb-2">
                <span>用户数量</span>
                <span className="font-medium text-gray-700 dark:text-gray-300">{role.userCount} 人</span>
              </div>
              <div className="flex justify-between text-sm text-gray-500 dark:text-gray-400">
                <span>创建时间</span>
                <span className="font-medium text-gray-700 dark:text-gray-300">{role.createdAt}</span>
              </div>
            </div>
            
            <div className="mb-4">
              <h4 className="text-sm font-medium text-gray-700 dark:text-gray-300 mb-2">权限列表</h4>
              <div className="flex flex-wrap gap-1">
                {role.permissions.map((permission, index) => (
                  <span 
                    key={index}
                    className="px-2 py-1 bg-blue-50 dark:bg-blue-900/20 text-blue-600 dark:text-blue-400 text-xs rounded-full"
                  >
                    {permission}
                  </span>
                ))}
              </div>
            </div>
            
            <div className="flex space-x-2">
              <button 
                className="flex-1 bg-blue-600 hover:bg-blue-700 text-white py-2 px-3 rounded-lg text-sm transition-colors duration-300"
                onClick={() => handleEditRole(role.id)}
              >
                编辑权限
              </button>
              <button 
                className={`flex-1 py-2 px-3 rounded-lg text-sm transition-colors duration-300 ${
                  role.status === '启用' 
                    ? 'bg-red-600 hover:bg-red-700 text-white' 
                    : 'bg-green-600 hover:bg-green-700 text-white'
                }`}
                onClick={() => handleToggleStatus(role.id, role.status)}
              >
                {role.status === '启用' ? '禁用' : '启用'}
              </button>
            </div>
          </div>
        ))}
        </div>
      )}
    </div>
  );
}